package com.nsgf.library;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.data.bean.MessageBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.repository.DataRepository;
import com.nsgf.library.data.response.DataResult;
import com.nsgf.library.databinding.ActivityNsgfRegionMainBinding;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.event.RxBus;
import com.nsgf.library.photopicker.utils.PermissionsUtils;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.MessageActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.ui.page.home.HomeMessageFragment;
import com.nsgf.library.ui.page.home.HomeReginFragment;
import com.nsgf.library.ui.page.home.MineFragment;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.view.MyRadioButton;
import com.nsgf.library.widget.prckerview.WebViewFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class MainNsgfRegionActivity extends BaseActivity {


    private LoginStates mStates;

    List<MyRadioButton> menuList;

    private BaseFragment pages[];
    private int lastIndexOfPage = 0;
    private long exitTime = 0L;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(LoginStates.class);

    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_nsgf_region_main, BR.vm, mStates)
                .addBindingParam(BR.clickProxy, new ClickProxy());
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBinding = (ActivityNsgfRegionMainBinding) getBinding();
        if (null == menuList) {
            menuList = new ArrayList<>();
            menuList.add(mBinding.rbHome);
            menuList.add(mBinding.rbPersonCenter);
            menuList.add(mBinding.rbTest);
            menuList.add(mBinding.rbManager);
        }

        pages = new BaseFragment[]{new HomeReginFragment(), WebViewFragment.newInstance(true), new HomeMessageFragment(), new MineFragment()};
        displayPage(0);

        startLocation();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            PermissionsUtils.checkPermissionFirst(this, 100,
                    new String[]{Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.RECEIVE_BOOT_COMPLETED});
        }

        EventBus.getDefault().register(this);
        RxBus.get().toObservable()
                .map((Function<Object, EventMsg>)
                        o -> (EventMsg) o)
                .subscribe((Consumer<EventMsg>) eventMsg -> {
                    if (eventMsg != null) {

                        if ("2".equals(eventMsg.getMsg())) {
                            modflyMenuStyle(mBinding.rbManager);
                            displayPage(2);
                            RxBus.get().hasObservers();
                        } else if ("badge".equals(eventMsg.getMsg())) {
                            mStates.badge.set(eventMsg.getContent());
                            mStates.badgeView.set(StringUtil.isEmpty("0".equals(eventMsg.getContent()) ? "" : eventMsg.getContent()) ? View.GONE : View.VISIBLE);
                        }
                    }
                });

        UserInfo.getInstance().setProjectCode("");
        UserInfo.getInstance().setProjectName("");
        getDatas(null);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMsg event) {
        if ("message".equals(event.getMsg())) {

            if ("0".equals(event.getContent())) {
                mStates.badgeView.set(View.GONE);
            } else {
                mStates.badge.set(event.getContent());
                mStates.badgeView.set(View.VISIBLE);
            }
        }
    }

    public static class LoginStates extends StateHolder {

        public final State<String> name = new State<>("");

        public final State<String> password = new State<>("");

        public final State<Boolean> loadingVisible = new State<>(false);

        public final State<String> badge = new State<>("");
        public final State<Integer> badgeView = new State<>(View.GONE);

    }

    private MyRadioButton lastChecked;

    private ActivityNsgfRegionMainBinding mBinding;

    public class ClickProxy {

        public void BottomClickHome() {
            modflyMenuStyle(mBinding.rbHome);
            displayPage(0);
        }

        public void BottomClickTest() {
            modflyMenuStyle(mBinding.rbTest);
            displayPage(1);
        }

        public void BottomClickManager() {
            modflyMenuStyle(mBinding.rbManager);
            displayPage(2);
        }

        public void BottomClickMine() {
            modflyMenuStyle(mBinding.rbPersonCenter);
            displayPage(3);
        }

        public void MessageModel() {
            startActivity(new Intent().setClass(MainNsgfRegionActivity.this, MessageActivity.class));
        }
    }


    /**
     * 修改menu样式
     *
     * @param rb
     */
    private void modflyMenuStyle(MyRadioButton rb) {
        rb.setChecked(true);
        for (MyRadioButton menuBtn : menuList) {
            if (menuBtn != rb) {
                menuBtn.setChecked(false);
            }
        }
        lastChecked = rb;
    }


    /**
     * @param index
     */
    public void displayPage(int index) {
        BaseFragment bf = pages[index];
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        FragmentManager fragmentManager = getSupportFragmentManager();
        if (bf.isAdded())
            ft.show(bf);
        else
            ft.add(R.id.content_container, bf);
        if (lastIndexOfPage < pages.length && lastIndexOfPage >= 0 && lastIndexOfPage != index)
            ft.hide(pages[lastIndexOfPage]);

        if (!fragmentManager.isDestroyed()) {
            ft.commit();
        }
        lastIndexOfPage = index;
    }

    /**
     * 内存重启后防止fragment出现重叠现象
     */
    private void whenMemoryReload() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for (Fragment f : fragments) {
            ft.hide(f);
        }
        ft.commitAllowingStateLoss();
    }

    MessageReceiver mMessageReceiver;

    public void registerMessageReceiver() {

        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION_BOTTOM);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION_BOTTOM.equals(intent.getAction())) {
                    modflyMenuStyle(mBinding.rbManager);
                    displayPage(2);
                }
            } catch (Exception e) {
            }
        }

    }

    /**
     * 监听返回次数，出应用
     */
    int clickTimes = 0;// 点击返回键次数

    @Override
    public void onBackPressed() {
        //不关闭页面，跳转到桌面
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            clickTimes++;
            java.util.Timer timer = new java.util.Timer(true);

            TimerTask task = new TimerTask() {
                public void run() {
                    clickTimes = 0;
                }
            };
            timer.schedule(task, 1600);

            if (clickTimes <= 1) {
                ToastUtils.showLongToast("再按一次退出应用");
            } else {
                finish();
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


    private int number = 0;

    /**
     * @param search
     */
    public void getDatas(String search) {
        DataRepository.getInstance().getMessage("message.type.2", search, null)
                .subscribe(new io.reactivex.Observer<DataResult<MessageBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(DataResult<MessageBean> dataResult) {
                        if (null != dataResult.getResult())
                            if (dataResult.getResult().getCode() == 200) {
                                for (MessageBean.DataBean messageBean : dataResult.getResult().getData()) {

                                    if (0 == messageBean.getIsRead()) {
                                        number++;
                                    }
                                }
                                mStates.badge.set(String.valueOf(number));
                                mStates.badgeView.set(number == 0 ? View.GONE : View.VISIBLE);
                            }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
